class UsersController < ApplicationController
  skip_before_filter :authorize, :only => [:login, :register]
  skip_before_filter :getGames, :only => [:login, :register]
  protect_from_forgery except: :login, except: :register
  
     def login
          if request.post? then
               username = ActionController::Base.helpers.sanitize params['username']
               password = ActionController::Base.helpers.sanitize params['password']
               u = User.authenticate(username, password)
               
               if u then
                    session[:user_id] = u.id
                    redirect_to dash_url
               else
                    @errors << "invalid username or password"   
               end
          end
     end

     def logout
          session[:user_id] = nil
          redirect_to root_url
     end

     def register
          if request.post? then
               username = ActionController::Base.helpers.sanitize params['username']
               firstname = ActionController::Base.helpers.sanitize params['firstname']
               password = ActionController::Base.helpers.sanitize params['password']
               email = ActionController::Base.helpers.sanitize params['email']
               
               @errors << 'username must be alphanumeric' unless username.match(/^\w+$/)
               @errors << 'passwords must match' unless params['password'] == params['confirm-password']
               @errors << 'first name cannot contain special characters' unless firstname == params['firstname']

               if @errors == [] then
                    u = User.new
                    u.username = username
                    u.password = password
                    u.email = email
                    u.firstname = firstname
                    u.active = Time.now
                    u.save
                    redirect_to login_url
               end
          end    
     end
end
